package com.cloudspace.yunloan.network;


import android.text.TextUtils;

import com.cloudspace.yunloan.R;
import com.cloudspace.yunloan.YunloanApp;
import com.cloudspace.yunloan.constants.Constants;
import com.cloudspace.yunloan.entity.BaseResult;
import com.cloudspace.yunloan.utils.ToastMaker;
import com.lzy.okhttputils.callback.AbsCallback;

import java.lang.reflect.ParameterizedType;
import java.net.SocketException;

import okhttp3.Call;
import okhttp3.Response;

public abstract class JsonCallBack<T> extends AbsCallback<T> {
    @Override
    public T parseNetworkResponse(Response response) throws Exception {
        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
        Class<T> clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
        String string = response.body().string();
        T obj = YunloanApp.getInstance().getGson().fromJson(string, clazz);

        if (obj instanceof BaseResult){
            BaseResult result = (BaseResult) obj;

            if (result != null && result.status != Constants.SUCCESS &&
                    !TextUtils.isEmpty(result.msg)){
                ToastMaker.showToastShort(result.msg);
            }
        }

        return obj;
    }

    @Override
    public void onError(Call call, Response response, Exception e) {
        super.onError(call, response, e);

        if (!(e instanceof SocketException)){
            ToastMaker.showToastShort(R.string.generic_error);
        }
    }
}